import React, {useEffect, useRef, useState} from 'react';
import {View, TouchableOpacity, StyleSheet, Animated} from 'react-native';
import {useAppTheme, Text} from 'tsun-smart-ui';

type Props = {
  tabs: Array<{
    key: string;
    title: string;
  }>;
  activeKey: string;
  onChange: (key: string, index: number) => void;
  className?: string;
  size?: 'small' | 'medium';
};

const Tab = ({
  tabs,
  activeKey,
  onChange,
  className,
  size = 'medium',
}: Props) => {
  const theme = useAppTheme();
  const [tabWidths, setTabWidths] = useState<{[key: string]: number}>({});
  const [tabPositions, setTabPositions] = useState<{[key: string]: number}>({});
  const indicatorAnim = useRef(new Animated.Value(0)).current;
  const indicatorWidthAnim = useRef(new Animated.Value(0)).current;

  // 当选中项变化时，执行动画
  useEffect(() => {
    const position = tabPositions[activeKey] || 0;
    const width = tabWidths[activeKey] || 0;
    Animated.parallel([
      Animated.spring(indicatorAnim, {
        toValue: position + width / 2 - 8,
        useNativeDriver: false,
        friction: 8,
        tension: 50,
      }),
      Animated.spring(indicatorWidthAnim, {
        toValue: width,
        useNativeDriver: false,
        friction: 8,
        tension: 50,
      }),
    ]).start();
  }, [activeKey, tabPositions, tabWidths]);

  // 测量每个Tab的宽度和位置
  const measureTab = (key: string, width: number, x: number) => {
    setTabWidths(prev => ({
      ...prev,
      [key]: width,
    }));
    setTabPositions(prev => ({...prev, [key]: x}));
  };

  return (
    <View
      className={`flex-row ${className} justify-around`}
      style={[styles.container, {height: size === 'small' ? 26 : 40}]}>
      {tabs.map((tab, index) => {
        const isActive = tab.key === activeKey;
        return (
          <TouchableOpacity
            key={tab.key}
            onPress={() => onChange(tab.key, index)}
            style={styles.tab}
            onLayout={e => {
              const {width, x} = e.nativeEvent.layout;
              measureTab(tab.key, width, x);
            }}>
            <Text
              variant={size === 'small' ? 'bodyMedium' : 'cardTitle'}
              style={[
                {
                  color: isActive
                    ? theme.colors?.brand?.primary
                    : theme.colors?.neutral?.title,
                },
              ]}>
              {tab.title}
            </Text>
          </TouchableOpacity>
        );
      })}

      {/* 指示器作为独立元素 */}
      <Animated.View
        style={[
          styles.indicator,
          {
            width: 16,
            backgroundColor: theme.colors?.brand?.primary,
            transform: [
              {
                translateX: indicatorAnim,
              },
            ],
          },
        ]}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    position: 'relative', // 确保容器是相对定位的
  },
  tab: {
    justifyContent: 'center',
    alignItems: 'center',
    height: '100%',
  },
  indicator: {
    position: 'absolute',
    bottom: -2,
    left: 0, // 从左侧开始
    height: 3,
    borderRadius: 4,
  },
});

export default Tab;
